package cn.pacerx.running.wx.task;

import cn.pacerx.running.core.task.Task;
import cn.pacerx.running.core.util.BeanUtil;
import cn.pacerx.running.db.domain.Activity;
import cn.pacerx.running.db.enums.ActivityStatusEnum;
import cn.pacerx.running.wx.service.ActivityService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ActivityExpiredTask extends Task {
    private final Log logger = LogFactory.getLog(ActivityExpiredTask.class);
    private long activityId = -1;

    public ActivityExpiredTask(Long activityId, long delayInMilliseconds) {
        super("ActivityExpiredTask-" + activityId, delayInMilliseconds);
        this.activityId = activityId;
    }

    @Override
    public void run() {
        logger.info("系统开始处理延时任务---活动过期---" + this.activityId);

        ActivityService activityService = BeanUtil.getBean(ActivityService.class);
        Activity activity = activityService.findById(this.activityId);
        if (activity == null) {
            return;
        }
        if (activity.getStatus() == ActivityStatusEnum.PROGRESSING) {
            // 设置活动已结束状态
            if (activityService.updateWithOptimisticLocker(activity, ActivityStatusEnum.ENDED) == 0) {
                throw new RuntimeException("更新数据失败，请重试");
            }
        }

        logger.info("系统结束处理延时任务---活动过期---" + this.activityId);
    }
}
